This method involves the programmer explicitly converting the data type using built-in functions like int(), float(), str() and str(). These functions act as constructors, creating a new object of the desired type.
Python has several built-in functions that can perform typecasting:
⮞
int(): This function converts a specified value into an integer. For example, int(3.5) will return 3.
⮞
float(): This function converts a specified value into a floating-point number. For example, float(3) will return 3.0.
⮞
str(): This function converts a specified value into a string. For example, str(100) will return '100'.
⮞
bool(): This function converts a specified value into a Boolean value (True or False). Non-zero values are considered True, while zero, None, and empty collections ([], {}, '', etc.) are considered False.
⮞
list(): This function converts a specified value into a list. For example, list('hello') will return ['h', 'e', 'l', 'l', 'o'].
⮞
tuple(): This function converts a specified value into a tuple. For example, tuple([1, 2, 3]) will return (1, 2, 3).
⮞
set(): This function converts a specified value into a set. For example, set([1, 2, 2, 3, 3, 3]) will return {1, 2, 3}.
⮞
dict(): This function converts a specified value into a dictionary. It requires a sequence of key-value pairs for the conversion. For example, dict([(1, 'one'), (2, 'two')]) will return {1: 'one', 2: 'two'}.
Remember, typecasting can sometimes lead to loss of information. For example, when you convert a floating-point number to an integer, the decimal part is discarded. Similarly, when you convert a complex number to an integer or a float, you’ll get a TypeError.
Also, not all types of conversions are allowed. For example, you cannot convert a string value that does not represent a number into an integer or a float. Doing so will raise a ValueError. For example, int('hello') will raise a ValueError.
It’s important to use typecasting wisely and understand the potential consequences of the conversion. It’s a powerful feature, but with great power comes great responsibility!
Here are some example for explicit typecasting
1. Integer (int)
Type casting - float to int, String to int example in python
number = 3.14
integer_value = int(number)
print(integer_value)
#Converting a string (assuming the string represents a valid integer)
text_number = "123"
int_value = int(text_number)
print(int_value)
Output
3
123
2. Float (float)
Type casting - int to float, String to float example in python
whole_number = 10
decimal_value = float(whole_number)
print(decimal_value)
#Converting a string (assuming the string represents a valid float):
decimal_text = "3.14"
float_value = float(decimal_text)
print(float_value)
Output
10.0
3.14
3. String (str)
Type casting - int to string, float to string example in python
# Converting an integer:
number = 42
string_value = str(number) # string_value will be "42"
print(string_value)
# Converting a float:
decimal_number = 3.14159
string_representation = str(decimal_number) # string_representation will be "3.14159" (may be truncated depending on precision settings)
print(string_representation)
Output
42
3.14159
4. Boolean (bool)
⯌ Non-zero integers are considered True in Python, so int(5) will implicitly cast to True.
⯌ Zero (int(0)) is considered False.
⯌ The strings "True" and "true" (case-insensitive) cast to True.
⯌ The strings "False" and "false" (case-insensitive) cast to False.
⯌ Any other string is considered False.
Type casting - int to boolean, str to boolean example in python
# Converting an integer:
number1 = 42
number2 = 0
bool_value1 = bool(number1)
bool_value2 = bool(number2)
print(bool_value1)
print(bool_value2)
str1 = "Tutorialsbox.com"
str2 = ""
bool_value1 = bool(str1)
bool_value2 = bool(str2)
print(bool_value1)
print(bool_value2)
Output
True
False
True
False
5. List (list)
There isn't a direct built-in function for converting to a list, but you can use various methods depending on the input data:⮞
If the input is an iterable (like a tuple, string, or another list), you can use list():
Python
Type casting - tuple to list example in python
tuple_data = (1, 2, 3)
list_from_tuple = list(tuple_data)
print(list_from_tuple)
Output
[1, 2, 3]
If the input is not directly iterable, you might need to create the list manually.
6. Tuple (tuple)
Similar to lists, there isn't a direct conversion function. You can use tuple() to create a tuple from an iterable:
Type casting - list to tuple example in python
list_data = [4, 5, 6]
tuple_from_list = tuple(list_data)
print(tuple_from_list)
Output
(4, 5, 6)
7. Dictionary (dict)
While there's no single function for direct conversion, you can create a dictionary from key-value pairs using curly braces ({}):
Typecasting - Converting data to dictionary example in python
name = "Alice"
age = 30
user_info = {"name": name, "age": age}
print(user_info)
Output
{'name': 'Alice', 'age': 30}
7. Set (set)
Type casting - list to set example in python
# List of numbers
numbers_list = [1, 2, 2, 3, 4, 4, 4, 5, 6]
numbers_set = set(numbers_list)
print(numbers_set)
Output
{1, 2, 3, 4, 5, 6}
Remember that successful explicit casting often depends on the initial data type and the validity of the conversion based on the target data type's constraints.